package framework.util.codeset;

import framework.util.codeset.bo.SysCodeset;
import framework.util.codeset.bo.SysCodesetDetail;
import framework.util.codeset.service.SysCodesetDetailService;
import framework.util.codeset.service.SysCodesetService;
import framework.util.codeset.vo.CodesetVo;
import framework.util.layui._LayuiUtil;
import framework.util.controller.BaseController;
import framework.util.queryFilter.service.impl.QueryFilter;
import framework.util.queryFilter.vo.Where;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 监听ac容器初始化完成后，对代码集的缓存初始化
 * @author 吴宇亮 on 2019/6/5 22:46
 */
public class CodesetInit implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SysCodesetService sysCodesetService = applicationContext.getBean("SysCodesetService", SysCodesetService.class);
        SysCodesetDetailService sysCodesetDetailService = applicationContext.getBean("SysCodesetDetailService", SysCodesetDetailService.class);

        List<SysCodeset> list = sysCodesetService.getAll(new QueryFilter(_LayuiUtil.FIRST_PAGE, Integer.MAX_VALUE));
        for (SysCodeset codeset : list) {
            //组装codesetDetail
            QueryFilter filter = new QueryFilter(_LayuiUtil.FIRST_PAGE, Integer.MAX_VALUE);
            filter.where(SysCodesetDetail.CLID, Where.eq, codeset.getLid());
            List<SysCodesetDetail> detailList = sysCodesetDetailService.getAll(filter);
            HashMap<String, String> detailMap = new HashMap<>(detailList.size());
            detailList.forEach(item -> {
                detailMap.put(item.getK(), item.getV());
                detailMap.put(item.getV(), item.getK());
            });
            //组装codeset
            BaseController.CODE.put(codeset.getCnName(), new CodesetVo(codeset.getLid(), codeset.getEnName(), detailList, detailMap));
            BaseController.CODE.put(codeset.getEnName(), new CodesetVo(codeset.getLid(), codeset.getCnName(), detailList, detailMap));
        }

        System.err.println("\n查询数据库缓存代码集成功！");
    }
}